package com.iguo.news.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iguo.news.common.QueryPageParam;
import com.iguo.news.entity.New;
import com.iguo.news.entity.R;
import com.iguo.news.entity.resultInfo.NewPageInfo;
import com.iguo.news.mapper.NewMapper;
import com.iguo.news.service.NewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/new")
public class NewController {

  @Autowired
  private NewMapper newMapper;

  @Autowired
  private NewService newService;

  @GetMapping("/get")
  public R<List<New>> getByContent(@RequestParam String content) {
    List<New> newsList = newService.searchByContentLike(content);
    return R.success(newsList);
  }


  @PostMapping("/listPage")
  public R<NewPageInfo> listPage(@RequestBody QueryPageParam pageParam) {
    log.info("new分页信息: num:{}, size:{}", pageParam.getPageNum(), pageParam.getPageSize());
    Page<New> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize(), true);
    LambdaQueryWrapper<New> queryWrapper = new LambdaQueryWrapper<>();
    if(!Objects.equals(pageParam.getNameInfo(), "")){
      queryWrapper.like(New::getContent, pageParam.getNameInfo());
    }
    int count = newMapper.selectCount(queryWrapper);
    IPage<New> result = newService.page(page, queryWrapper);

    NewPageInfo info = new NewPageInfo();
    info.setNewList(result.getRecords());
    info.setCount(count);
    return R.success(info);
  }


  @PutMapping("/update")
  public R<String> update(@RequestBody New news) {
    log.info("更新的新闻ID: {}, 内容: {}", news.getId(), news.getContent());
    return newService.updateById(news) ? R.success("更新成功") : R.error("更新失败");
  }

}